<template>
  <div class="expert-qa">
    <div class="page-header">
      <h2>线上答疑</h2>
    </div>

    <!-- 等待答疑列表 -->
    <div v-if="!currentSession" class="waiting-list">
      <h3>等待答疑的农户</h3>
      <div class="farmer-list">
        <div 
          v-for="farmer in waitingFarmers" 
          :key="farmer.id" 
          class="farmer-card"
          :class="{ 'ready': isReadyToStart(farmer) }"
        >
          <div class="farmer-info">
            <div class="farmer-avatar">{{ farmer.name.charAt(0) }}</div>
            <div class="farmer-details">
              <h4>{{ farmer.name }}</h4>
              <p class="problem-preview">{{ farmer.problem }}</p>
              <div class="appointment-time">
                <i class="fas fa-clock"></i>
                {{ farmer.appointmentTime }}
              </div>
            </div>
          </div>
          <div class="farmer-actions">
            <button 
              class="btn primary-btn" 
              @click="startSession(farmer)"
              :disabled="!isReadyToStart(farmer)"
            >
              {{ isReadyToStart(farmer) ? '开始答疑' : '等待时间' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="waitingFarmers.length === 0" class="empty-state">
        <div class="empty-icon">💬</div>
        <h3>暂无等待答疑的农户</h3>
        <p>农户的预约将在到达时间后显示在这里</p>
      </div>
    </div>

    <!-- 答疑会话界面 -->
    <div v-else class="qa-session">
      <div class="session-header">
        <div class="expert-info-header">
          <div class="expert-avatar-header">{{ currentExpert.name.charAt(0) }}</div>
          <div class="expert-details-header">
            <h3>{{ currentExpert.name }}</h3>
            <p class="expert-title-header">{{ currentExpert.title }}</p>
          </div>
        </div>
        <div class="session-info">
          <div class="chat-actions">
            <!-- 问题详情按钮 -->
            <el-button type="primary" text @click="showProblemDetail = true">
              <el-icon><Document /></el-icon>
              问题详情
            </el-button>
          </div>
          <span class="session-timer">
            <i class="fas fa-clock"></i>
            {{ formatTimeCount(sessionTimer) }}
          </span>
          <button class="button" @click="endSession">
            <i class="fas fa-times"></i> 结束答疑
          </button>
        </div>
      </div>

      <div class="chat-container">
        <div class="messages-container" ref="messagesContainer">
          <div 
            v-for="message in currentSession.messages" 
            :key="message.id"
            class="message"
            :class="message.sender"
          >
            <div class="message-content">
              {{ message.content }}
            </div>
            <div class="message-time">
              {{ message.time }}
            </div>
          </div>
        </div>

        <div class="message-input">
          <textarea 
            v-model="newMessage" 
            placeholder="请输入您的回复..."
            rows="3"
            @keypress.enter.prevent="sendMessage"
          ></textarea>
          <button class="btn primary-btn" @click="sendMessage" :disabled="!newMessage.trim()">
            <i class="fas fa-paper-plane"></i> 发送
          </button>
        </div>
      </div>
    </div>
  </div>

<!-- 问题详情对话框 -->
  <el-dialog
    v-model="showProblemDetail"
    title="问题详情"
    width="500px"
    :close-on-click-modal="false"
  >
    <div class="problem-detail-content">
      <div class="detail-item">
        <span class="label">咨询问题:</span>
        <span class="value">{{ problemDetail.problemDescription }}</span>
      </div>
      
      <div class="detail-item">
        <span class="label">预约类型:</span>
        <span class="value">{{ problemDetail.appointmentType === 1 ? '线上答疑' : '线下预约' }}</span>
      </div>
      
      <div class="detail-item">
        <span class="label">开始时间:</span>
        <span class="value">{{ formatTime(problemDetail.startTime) }}</span>
      </div>
      
      <div class="detail-item">
        <span class="label">咨询状态:</span>
        <span class="value">
          <el-tag type="success" size="small">进行中</el-tag>
        </span>
      </div>
    </div>
  </el-dialog>

  <!-- 结束确认对话框 -->
  <el-dialog
    v-model="showEndConfirm"
    title="结束答疑"
    width="400px"
    :close-on-click-modal="false"
  >
    <div class="end-confirm-content">
      <p>确定要结束本次答疑吗？</p>
    </div>
    <template #footer>
      <el-button @click="showEndConfirm = false">取消</el-button>
      <el-button type="primary" @click="confirmEndSession">确定</el-button>
    </template>
  </el-dialog>

  <!-- 总结对话框 -->
  <el-dialog
    v-model="showSummaryDialog"
    title="答疑总结"
    width="600px"
    :close-on-click-modal="false"
    :show-close="false"
  >
    <div class="summary-form">
      <el-form :model="summaryForm" label-width="80px">
        <el-form-item label="主要问题" required>
          <el-input
            v-model="summaryForm.mainProblem"
            type="textarea"
            :rows="3"
            placeholder="请输入农户咨询的主要问题"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="解决方案" required>
          <el-input
            v-model="summaryForm.solution"
            type="textarea"
            :rows="3"
            placeholder="请输入具体的解决方案和建议措施"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="建议" required>
          <el-input
            v-model="summaryForm.suggestion"
            type="textarea"
            :rows="2"
            placeholder="请输入其他建议和注意事项"
            maxlength="150"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" @click="saveSummary" style="width: 120px;">
        保存总结
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const currentSession = ref(null)
const newMessage = ref('')
const sessionTimer = ref(0)
const messagesContainer = ref(null)
let timerInterval = null

const showProblemDetail = ref(false) // 控制问题详情对话框显示
const showEndConfirm = ref(false) // 控制结束确认对话框
const showSummaryDialog = ref(false) // 控制总结对话框

// 总结表单数据
const summaryForm = reactive({
  mainProblem: '',
  solution: '',
  suggestion: ''
})

// 当前专家信息
const currentExpert = ref({
  name: '张教授',
  title: '农业种植专家'
})

// 等待答疑的农户列表
const waitingFarmers = ref([
  {
    id: 1,
    name: '李农户',
    problem: '关于黄瓜种植的土壤要求咨询',
    appointmentTime: '15:00',
    appointmentDate: '2024-01-25',
    status: 'ready'
  },
  {
    id: 2,
    name: '王种植户',
    problem: '果树修剪技术指导',
    appointmentTime: '16:30',
    appointmentDate: '2024-01-25',
    status: 'waiting'
  }
])

// 问题详情
const problemDetail = reactive({
  id: 1,
  problemDescription: '关于西红柿种植过程中的病虫害防治问题，特别是针对白粉病和蚜虫的有效防治方法。',
  appointmentType: 1,
  startTime: new Date().toISOString(),
  status: 1
})

// 方法
const isReadyToStart = (farmer) => {
  return farmer.status === 'ready'
}

const startSession = (farmer) => {
  currentSession.value = {
    farmerId: farmer.id,
    farmerName: farmer.name,
    startTime: new Date(),
    messages: [
      {
        id: 1,
        sender: 'farmer',
        content: farmer.problem,
        time: '15:00'
      }
    ]
  }
  
  // 开始计时
  sessionTimer.value = 0
  timerInterval = setInterval(() => {
    sessionTimer.value++
  }, 1000)

  // 从等待列表中移除
  waitingFarmers.value = waitingFarmers.value.filter(f => f.id !== farmer.id)
  scrollToBottom()
}

const endSession = () => {
  // 显示确认对话框
  ElMessageBox.confirm('确定要结束本次答疑吗？', '结束答疑', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    customClass: 'end-session-confirm'
  }).then(() => {
    // 用户确认结束
    if (timerInterval) {
      clearInterval(timerInterval)
    }
    
    // 保存会话记录
    if (currentSession.value) {
      const sessionRecord = {
        ...currentSession.value,
        endTime: new Date(),
        duration: sessionTimer.value
      }
      console.log('保存会话记录:', sessionRecord)
    }
    
    // 显示总结对话框
    showSummaryDialog.value = true
    
  }).catch(() => {
    // 用户取消，什么都不做
    console.log('用户取消结束答疑')
  })
}

const saveSummary = () => {
  // 验证表单
  if (!summaryForm.mainProblem.trim() || !summaryForm.solution.trim() || !summaryForm.suggestion.trim()) {
    ElMessage.error('请填写完整的总结信息')
    return
  }
  
  // 保存总结数据
  const summaryData = {
    sessionId: currentSession.value?.farmerId,
    ...summaryForm,
    endTime: new Date(),
    duration: sessionTimer.value
  }
  
  console.log('保存总结数据:', summaryData)
  
  // 重置表单和状态
  resetSummaryForm()
  showSummaryDialog.value = false
  currentSession.value = null
  sessionTimer.value = 0
  
  ElMessage.success('答疑总结已保存')
}

const resetSummaryForm = () => {
  summaryForm.mainProblem = ''
  summaryForm.solution = ''
  summaryForm.suggestion = ''
}

const sendMessage = () => {
  if (!newMessage.value.trim()) return

  const message = {
    id: Date.now(),
    sender: 'expert',
    content: newMessage.value,
    time: new Date().toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }

  currentSession.value.messages.push(message)
  newMessage.value = ''

  // 模拟农户回复
  setTimeout(() => {
    const farmerReply = {
      id: Date.now() + 1,
      sender: 'farmer',
      content: '谢谢专家！我明白了，我会按照您说的方法去处理。',
      time: new Date().toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    }
    currentSession.value.messages.push(farmerReply)
    scrollToBottom()
  }, 2000)

  scrollToBottom()
}

const formatTimeCount = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const formatTime = (timeString) => {
  return new Date(timeString).toLocaleString('zh-CN')
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

onMounted(() => {
  // 可以在这里加载等待答疑的农户列表
})

onUnmounted(() => {
  if (timerInterval) {
    clearInterval(timerInterval)
  }
})
</script>

<style scoped>
.expert-qa {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  color: #333;
  font-size: 24px;
  margin: 0;
}

.waiting-list h3 {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
}

.farmer-list {
  display: grid;
  gap: 15px;
}

.farmer-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-left: 4px solid #FF9800;
  transition: all 0.3s ease;
}

.farmer-card.ready {
  border-left-color: #4CAF50;
}

.farmer-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0,0,0,0.15);
}

.farmer-info {
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
}

.farmer-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #2196F3, #1976D2);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 20px;
  flex-shrink: 0;
}

.farmer-details h4 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.problem-preview {
  color: #666;
  margin: 0 0 8px 0;
  font-size: 14px;
}

.appointment-time {
  color: #999;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.farmer-actions {
  flex-shrink: 0;
}

/* 答疑会话界面 */
.qa-session {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  overflow: hidden;
}

.session-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
}

.expert-info-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.expert-avatar-header {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4CAF50, #2E7D32);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 18px;
}

.expert-details-header h3 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 18px;
}

.expert-title-header {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.session-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.session-timer {
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 600px;
}

.messages-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.message.farmer {
  align-self: flex-start;
}

.message.expert {
  align-self: flex-end;
}

.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
}

.message.farmer .message-content {
  background: white;
  color: #333;
  border: 1px solid #e0e0e0;
  border-bottom-left-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.message.expert .message-content {
  background: #4CAF50;
  color: white;
  border-bottom-right-radius: 4px;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 5px;
  padding: 0 8px;
}

.message-input {
  padding: 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.message-input textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
}

.message-input textarea:focus {
  outline: none;
  border-color: #4CAF50;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.primary-btn {
  background: #4CAF50;
  color: white;
}

.primary-btn:hover:not(:disabled) {
  background: #45a049;
  transform: translateY(-1px);
}

/* From Uiverse.io by gharsh11032000 */ 
.button {
  cursor: pointer;
  position: relative;
  padding: 10px 24px;
  font-size: 18px;
  color: rgb(193, 163, 98);
  border: 2px solid rgb(193, 163, 98);
  border-radius: 34px;
  background-color: transparent;
  font-weight: 600;
  transition: all 0.3s cubic-bezier(0.23, 1, 0.320, 1);
  overflow: hidden;
}

.button::before {
  content: '';
  position: absolute;
  inset: 0;
  margin: auto;
  width: 50px;
  height: 50px;
  border-radius: inherit;
  scale: 0;
  z-index: -1;
  background-color: rgb(193, 163, 98);
  transition: all 0.6s cubic-bezier(0.23, 1, 0.320, 1);
}

.button:hover::before {
  scale: 3;
}

.button:hover {
  color: #212121;
  scale: 1.1;
  box-shadow: 0 0px 20px rgba(193, 163, 98,0.4);
}

.button:active {
  scale: 1;
}

/* 问题详情对话框样式 */
.problem-detail-content {
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-item .label {
  color: #718096;
  font-size: 14px;
  min-width: 80px;
}

.detail-item .value {
  color: #2d3748;
  font-weight: 500;
  flex: 1;
}

/* 问题详情对话框样式 */
.session-info {
  margin-bottom: 20px;
}

.attachments-title {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
}

.attachments-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.file-icon {
  font-size: 24px;
  color: #409eff;
}

.file-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 2px;
}

.file-size {
  font-size: 12px;
  color: #909399;
}

/* 总结表单样式 */
.summary-form {
  padding: 20px 0;
}

.summary-form .el-form-item {
  margin-bottom: 20px;
}

.summary-form .el-textarea__inner {
  resize: vertical;
  min-height: 80px;
}

/* 确认对话框样式 */
.end-confirm-content {
  text-align: center;
  padding: 20px 0;
  font-size: 16px;
  color: #606266;
}

.end-confirm-content p {
  margin: 0;
}

/* 自定义确认对话框样式 */
.end-session-confirm .el-message-box__content {
  padding: 20px;
}

.end-session-confirm .el-message-box__status {
  font-size: 24px !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .expert-qa {
    padding: 16px;
  }
  
  .farmer-card {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .farmer-actions {
    align-self: flex-end;
  }
  
  .session-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .session-info {
    align-self: flex-end;
  }
  
  .message {
    max-width: 85%;
  }
  
  .message-input {
    flex-direction: column;
  }
  
  .message-input button {
    width: 100%;
  }
}
</style>